package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-07 15:17
 **/

@Service
public class UserService {




    //调用dubbio服务
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    //redis
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    public User findByMobile(String mobile) {
        User user = userApi.findByMobile(mobile);

        return user;
    }



    //登录校验
    public Map loginVerification(String phone, String code) {
        //1.获取redis中的验证码
        String rediscode = redisTemplate.opsForValue().get("CODE:" + phone);
        //2.比较用户输入的验证码和redis验证码是否一致
        if(StringUtils.isEmpty(rediscode) || !rediscode.equals(code)){
            //2.2 不一致，抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }
        //2.1一致，删除redis中的验证码数据
        redisTemplate.delete("CODE:"+phone);
        //3.根据手机号码查询用户
        User user = userApi.findByMobile(phone);
        //4. 手机不存在，新用户，注册用户（数据保存到用户表）
        Boolean isNew = false;
        String type = "0101";//登录
        if(user == null){
            isNew = true;
            user =  new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long userId = userApi.save(user);
            user.setId(userId);
            //把用户信息注册到环信中
            huanXinTemplate.createUser("hx"+user.getId(),"123456");
            //更新用户的环信账号和密码
            user.setHxUser("hx"+user.getId());
            user.setHxPassword("123456");
            userApi.update(user);
            type = "0102";//注册
        }
//        Map msg = new HashMap();
//        msg.put("userId",user.getId());
//        msg.put("type",type);
//        String logtime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        msg.put("logTime",logtime);
//
//
//        String message = JSON.toJSONString(msg);
//        //登录成功，发送日志消息
//        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",message);//交换机，路由键，消息
        mqMessageService.sendLogMessage(user.getId(),type,"log.user",null);

        //5.生成jwt的token字符串
        Map tokenmap = new HashMap();
        tokenmap.put("id",user.getId());
        tokenmap.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(tokenmap);
        //6.构建返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return  retMap;
    }

    /*保存用户资料

    * */
    public void saveUserInfo(UserInfo userInfo) {
        //调用api保存用户信息
        userInfoApi.save(userInfo);
    }

    /*
    * 设置头像
    * */
    public void head(Long id, MultipartFile headPhoto) throws IOException {
        //1.上传到阿里云oss
        String url = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());//文件流，文件名

        //2.头像是否包含人脸
        Boolean detect = aipFaceTemplate.detect(url);
        if(!detect){
            //不包含人脸
            throw  new  BusinessException(ErrorResult.faceError());
        }
        //3.调用api，更新userInfo
        //MP中，只需要指定id和需要更新的字段对象即可
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);
    }
}
